<?php
namespace App\Repositories;

use App\Models\Coach;
use App\Models\Comment;
use App\Models\Complaint;
use App\Models\Evaluate;
use App\Models\Outlet;
use App\Models\School;
use App\Models\Service;
use App\Models\Student;
use App\Models\StudentCount;
use App\Models\StudentState;
use App\Models\StudentCoach;
use App\Models\Style;
use App\Models\Subscribe;
use App\Models\TcpPutime;
use App\Models\TcpStudytime;
use App\Models\AppBanner;
use App\Models\StudentConfig;
use App\Models\Trainingcar;
use Carbon\Carbon;

class StudentRepository extends BaseRepository
{
    public $error = '';
    public function __construct(
        Student $student
    )
    {
        $this->model = $student;
    }

    /**
     * 资源列表
     * @param  array $param 必须传入与模型查询相关的数据
     * @param  string|array $extra 可选额外传入的参数
     * @param  string $size 分页大小（存在默认值）
     * @return Illuminate\Support\Collection
     */
    public function index($param=[], $extra='', $size='10')
    {

    }

    /**
     * 学员首页
     * @param $stuid
     * @return array
     */
    public function getStudentInfo($stuid)
    {
        $data = [];


        //获取学员信息
        $student = $this->getById($stuid);

        //获取最新的培训科目
        $latest_train = TcpStudytime::select('starttime','endtime','km','created_at')->orderBy('created_at', 'desc')->first();

        $latest_train->valid_putime = TcpPutime::where('stunum',$latest_train->stunum)->where('classid',$latest_train->classid)->where('jishi_check',1)->where('jg_check',1)->count();//有效学时
        $latest_train->novalid_putime = TcpPutime::where('stunum',$latest_train->stunum)->where('classid',$latest_train->classid)->where('jg_check',2)->count();//无效学时

        $data['latest_train'] = $latest_train;

        $data['student'] = $student;

        $config = StudentConfig::where('student_id', $student->id)->first();
        $data['config'] = $config ? $config : [];

        return $data;
    }
    

    /**
     * 存储odb
     * @param $inputs
     */
    public function store($inputs, $extra = '')
    {

    }


    /**
     * 更新
     * @param $id
     * @param $input
     * @return mixed
     */
    public function update($id, $input,$extra = '')
    {
        $model = $this->getById($id);
        return $this->save($model,$input);
    }


    /**
     * 编辑特定id资源
     * @param  int $id 资源id
     * @param  string|array $extra 可选额外传入的参数
     * @return Illuminate\Support\Collection
     */
    public function edit($id, $extra)
    {

    }

    /**
     * @param $model
     * @param $inputs
     * @param bool $falg
     * @return mixed
     */
    public function save($model , $inputs , $falg = false)
    {
        return $model;
    }



    /*
     * 获取学员的个人中心
     */
    public function mycenter(Student $student_info)
    {
        $data = $this->model->select('students.name','students.photo','students.traintype','schools.shortname')
                            ->leftJoin('schools', 'students.school_id', '=', 'schools.id')
                            ->where('students.id', $student_info->id)
                            ->first();
        $data->traintype = traintypeName($data->traintype);
        $data->mycomment = Comment::where('student_id', $student_info->id)->count() + Evaluate::where('stunum', $student_info->stunum)->count();
        $data->mycomplain = StudentState::where('student_id', $student_info->id)->count();


        $info = StudentCount::where('student_id', $student_info->id)->first();

        $data->mywallet = 0;

        $data->service_tel = '';

        if($student_info->service_id){
            $data->service_tel = $student_info->service->service_tel;
        }

        if($info && $student_info->service_id && $student_info->service->paymode == 2){
            $data->mywallet = $info->km2period + $info->km3period;
        }

        return $data;
    }


    /**
     * 我的驾校
     */
    public function mySchool(Student $student_info)
    {
        $school_info = $student_info->school;

        //驾校基本信息
        $school['id'] = $school_info->id;
        $school['name'] = $school_info->shortname;
        $school['busiscope'] = $school_info->busiscope;
        $school['address'] = $school_info->address;
        $school['phone'] = $school_info->phone;
        $school['photo'] = '';
        $school['coach_count'] = Coach::where('school_id', $school_info->id)->where('employstatus', 0)->count();
        $school['car_count'] = Trainingcar::where('school_id', $school_info->id)->count();
        $school['evaluate_total'] = Evaluate::where('type', 2)->where('evalobject', $school_info->inscode)->count();
        $school['evaluate_perfect'] = Evaluate::where('type', 2)->where('evalobject', $school_info->inscode)->where('overall', 5)->count();
        $school['evaluate_good'] = Evaluate::where('type', 2)->where('evalobject', $school_info->inscode)->whereBetween('overall', [2,4])->count();
        $school['evaluate_normal'] = Evaluate::where('type', 2)->where('evalobject', $school_info->inscode)->where('overall', 1)->count();
        $school['photo'] = '';
        $school['evaluate_rate'] = $school['evaluate_total'] ? number_format(($school['evaluate_good'] + $school['evaluate_perfect']) / $school['evaluate_total'], 2) : 0;

        $school_style = Style::where('type',1)->where('item_id',$school_info->id)->first();
        $school['logo'] = $school_style ? $school_style->logo : '';
        $school['style_pic'] = $school_style ? json_decode($school_style->pic) : [];
        $school['description'] = $school_style ? $school_style->content : '';

        return $school;
    }


    /**
     * 我的教练
     */
    public function myCoachs(Student $student_info)
    {
        $subscrib_list = Subscribe::leftJoin('yy_put_periods', 'yy_put_periods.id', '=', 'yy_subscribes.putime_id')
                            ->leftJoin('coachs', 'coachs.id', '=', 'yy_subscribes.coach_id')
                            ->select('yy_subscribes.*','yy_put_periods.km','coachs.name as coachname','coachs.coachnum','coachs.photo','coachs.mobile')
                            ->where('student_id', $student_info->id)
                            ->groupBy('coach_id')
                            ->get();
        if($subscrib_list){
            $data = ['km2' => [], 'km3' => []];
            foreach($subscrib_list as $subscrib){
                $subscrib->evaluate_total = Comment::where('coach_id', $subscrib->coach_id)->count();
                $subscrib->evaluate_perfect = Comment::where('comment', 2)->where('coach_id', $subscrib->coach_id)->count();
                $subscrib->evaluate_good = Comment::where('comment', 1)->where('coach_id', $subscrib->coach_id)->count();
                $subscrib->evaluate_normal = Comment::where('comment', 0)->where('coach_id', $subscrib->coach_id)->count();
                $subscrib->evaluate_rate =  $subscrib->evaluate_total ? number_format(($subscrib->evaluate_good + $subscrib->evaluate_perfect) / $subscrib->evaluate_total,2) : 0;
                $subscrib->student_count = Subscribe::where('coach_id', $subscrib->coach_id)->groupBy('student_id')->count();
                $subscrib->distance = 0;

                if($subscrib['km'] == 2){
                    $data['km2'][] = $subscrib;
                }elseif($subscrib['km'] == 3){
                    $data['km3'][] = $subscrib;
                }
            }

            return $data;
        }

        return [];
    }
    public function getAllToWhere($arr=[], $size, $page)
    {
        $query = StudentCoach::leftJoin('students as stu','stu.id','=','student_coach.stuid');
        if(!empty($arr['coach_id'])) $query = $query->where('student_coach.cid',$arr['coach_id']);
        if(!empty($arr['keyword'])) $query = $query->where('stu.name', 'like', '%'.$arr['keyword'].'%');
        return $query->select('stu.id','stu.name','stu.photo','stu.phone','stu.graduation')->where('stu.graduation', 0)
                    ->groupBy('student_coach.stuid')
                    ->limit($size)->offset(($page - 1) * $size)->get()->toArray();
    }


    //驾校学员管理列表
    public function schoolStudentReport(School $school)
    {
        $list['stu_count'] = $this->model->where('school_id', $school->id)->count();
        $list['stu_new'] = $this->model->where('school_id', $school->id)
                                            ->whereBetween('applydate', [date('Y-m-01'),date('Y-m-t')])->count();

        $lf_day = Carbon::createFromFormat('Y-m-d',date('Y-m-01'))->subMonth(1)->day;
        $ll_day = Carbon::createFromFormat('Y-m-d',date('Y-m-01'))->subDay(1)->day;

        $outlets = Outlet::where('school_id', $school->id)->get();
        $list['outlets_info'] = $outlets_info = [];
        if($outlets){
            foreach ($outlets as $outlet) {
                $outlets_info['name'] = $outlet->name;
                $outlets_info['charge_man'] = $outlet->charge;
                $outlets_info['this_month'] = $this->model->where('outlets_id', $outlet->id)->whereBetween('applydate', [date('Y-m-01'),date('Y-m-t')])->count();
                $outlets_info['last_month'] = $this->model->where('outlets_id', $outlet->id)->whereBetween('applydate', [$lf_day, $ll_day])->count();
                $outlets_info['total'] = $this->model->where('outlets_id', $outlet->id)->count();
                $list['outlets_info'][] = $outlets_info;
            }
        }

        $service = Service::where('school_id', $school->id)->get();
        $list['service_info'] = $service_info = [];
        if($service){
            foreach ($service as $sv) {
                $service_info['name'] = $sv->classcurr;
                $service_info['this_month'] = $this->model->where('service_id', $sv->id)->whereBetween('applydate', [date('Y-m-01'),date('Y-m-t')])->count();
                $service_info['last_month'] = $this->model->where('service_id', $sv->id)->whereBetween('applydate', [$lf_day, $ll_day])->count();
                $service_info['total'] = $this->model->where('service_id', $sv->id)->count();
                $list['service_info'][] = $service_info;
            }
        }

        $car_type = explode(',', $school->busiscope);
        $list['cartype_info'] = $cartype_info = [];
        if(!empty($car_type)){

            foreach ($car_type as $type){
                $cartype_info['name'] = $type;
                $cartype_info['this_month'] = $this->model->where('school_id', $school->id)->where('traintype', $type)->whereBetween('applydate', [date('Y-m-01'),date('Y-m-t')])->count();
                $cartype_info['last_month'] = $this->model->where('school_id', $school->id)->where('traintype', $type)->whereBetween('applydate', [$lf_day, $ll_day])->count();
                $cartype_info['total'] = $this->model->where('school_id', $school->id)->where('traintype', $type)->count();
                $list['cartype_info'][] = $cartype_info;
            }
        }


        return $list;
    }
}